#!/bin/bash
#-----------------------------------------------------------------------#
HERE=`pwd`

OPENWRT=http://lede-project.tetaneutral.net/snapshots/targets/x86/64

ROOTFS=/root/openwrt
OFFSET=17301504
OFFSET_BOOT=262144
OPENWRT_IMG=openwrt-x86-64-combined-ext4.img

for i in qemu-img gunzip wget; do
  path_bin=$(which $i)
  if [ -z $path_bin ]; then
    echo $i  DOES NOT EXIST
    exit -1
  fi
done

if [ $UID != 0 ]; then
  echo you must be root
  exit -1
fi
modprobe loop
if [[ "$(losetup -a )" != "" ]]; then
  echo
  echo
  echo losetup -a should give nothing, it gives:
  losetup -a
  echo
  exit -1
fi
#---------------------------------------------------------------------------#
  mkdir -p /tmp/wkmntloops
  wget --no-check-certificate ${OPENWRT}/${OPENWRT_IMG}.gz
  gunzip ${OPENWRT_IMG}.gz
  qemu-img convert -O raw ${OPENWRT_IMG} $ROOTFS
  rm ${OPENWRT_IMG}
  losetup /dev/loop0 $ROOTFS
  losetup -o $OFFSET /dev/loop1 /dev/loop0
  mount /dev/loop1 /tmp/wkmntloops
#--------------------------------------------------------------------#
if [ -e /etc/resolv.conf ]; then
  cp -f /etc/resolv.conf "/tmp/wkmntloops/tmp"
fi
#-----------------------------------------------------------------------#
  cat > /tmp/wkmntloops/chroot_cmds  << "EOF"
#!/bin/ash
mkdir /var/lock/
sleep 1
opkg update
sleep 1
opkg install kmod-scsi-cdrom
opkg install kmod-fs-isofs
passwd << "INEOF"
rootroot
rootroot
INEOF
EOF

  chmod +x /tmp/wkmntloops/chroot_cmds
  chroot /tmp/wkmntloops /chroot_cmds

  umount /tmp/wkmntloops
  losetup -d /dev/loop1
  losetup -d /dev/loop0
  cd /root
  qemu-img convert -O qcow2 openwrt openwrt.qcow2
  rm -f openwrt
#---------------------------------------------------------------------#




